package it.polito.let.java;

import java.util.HashSet;
import java.util.Set;


public class JavaMethod {

	private String[] modifiers;
	private String type;
	private String[] params;
	private String name;
	private String ID;
	private StringBuffer statement;
	private Set<String> throwList = new HashSet<String>();

	protected JavaMethod(String[] modifiers,String type, String name, String[] params) {
		this.modifiers = modifiers;
		this.type = type;
		this.name = name;
		this.params = params;
		this.ID = toID(name,params);
		this.statement = new StringBuffer();
	}

	public String getID() {
		return ID;
	}

	public void appendStatement(String stmt) {
		statement.append(stmt+"\n");
	}

	public String getStatement() {
		return statement.toString();
	}

	public static String toID(String name, String[] params) {
		StringBuffer s = new StringBuffer(name+"_");
		if (params != null)
			for (String p:params)
				s.append(p);
		return s.toString().replaceAll("\\s*", "");
	}

	public String toString() {
		StringBuffer result = new StringBuffer();

		for (String m:modifiers)
			result.append(m+" ");
		result.append(type +" ");
		if (name != null)
			result.append(name+" ");
		result.append("(");
		boolean first = true;
		if (params != null)
			for (String p:params) {
				if (first)
					first = false;
				else
					result.append(", ");
				result.append(p);
			}
		result.append(") ");
		if (throwList.size() > 0) {
			result.append("throws ");
			for (String t:throwList)
				result.append(t+" ");
		}	
		result.append("{\n");
		result.append(statement);
		result.append("}\n\n");
		return result.toString();
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((getID() == null) ? 0 : getID().hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (!(obj instanceof JavaMethod))
			return false;
		JavaMethod other = (JavaMethod) obj;
		if (getID() == null) {
			if (other.getID() != null)
				return false;
		} else if (!getID().equals(other.getID()))
			return false;
		return true;
	}

	public void addThrow(String exc) {
		throwList .add(exc);
	}

}
